# ~*~ coding: utf-8 ~*~
from .models import Asset, SystemUser, AssetPermissionRelated, AssetPermission
from apps.extensions import db


class AssetMixin(object):

    def get_related_assets(self):
        """
        :return:
         {
            '82a7c4ec-87d2-41ed-a5f1-0a96d400014e': {
                'asset': < Asset a96d400014e > ,
                'system_users': [ < SystemUser A > , < SystemUser B > ]
            },
            '6db5a983-aac7-49fa-8aa8-3de4ce2dcd0f': {
                'asset': < Asset de4ce2dcd0f > ,
                'system_users': [ < SystemUser A > , < SystemUser B > ]
            }
        }
        """
        hosts = db.session.query(AssetPermissionRelated.id, Asset, SystemUser). \
            join(Asset, Asset.id == AssetPermissionRelated.asset_id). \
            join(SystemUser, SystemUser.id == AssetPermissionRelated.system_user_id). \
            filter(AssetPermissionRelated.user_id == self.id). \
            all()

        response = {}
        for _, asset, system_user in hosts:
            if asset.id not in response.keys():
                response[asset.id] = {
                    'asset': asset,
                    'system_users': [system_user]
                }
            else:
                if system_user not in response[asset.id]['system_users']:
                    response[asset.id]['system_users'].append(system_user)
        return response

    def has_asset_action_perm(self, asset, system_user, action):
        granted_permissions = db.session.query(AssetPermissionRelated.id, AssetPermission).\
            join(AssetPermission, AssetPermissionRelated.asset_permission_id == AssetPermission.id).\
            filter(
                AssetPermissionRelated.user_id == self.id,
                AssetPermissionRelated.asset_id == asset.id,
                AssetPermissionRelated.system_user_id == system_user.id,
            ).\
            all()

        check_actions = []
        for _, granted_permission in granted_permissions:
            check_actions.append(granted_permission.check_action_perm(action))
        return any(check_actions)

    def has_asset_connect_perm(self, asset, system_user):
        granted_permissions = db.session.query(AssetPermissionRelated.id, AssetPermission). \
            filter(
                AssetPermissionRelated.user_id == self.id,
                AssetPermissionRelated.asset_id == asset.id,
                AssetPermissionRelated.system_user_id == system_user.id,
            ). \
            count()
        if granted_permissions:
            return True
        else:
            return False
